<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\admin\service\JobCategoryService;
use app\admin\service\JobService;
use think\facade\View;

class Job extends Diluma
{
    /**
     * @return mixed
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 列表数据
     * @return \think\response\Json
     */
    public function getJobList(){
        $service = new JobCategoryService();
        $items = $service->getJobCategoryList();
        return json(['code'=>0, 'count'=>$items->total(), 'data'=>$items->items()]);
    }

    /**
     * 获取子分类
     * @return \think\response\Json|void
     */
    public function getJobCategory(){
        $post = $this->request->post();
        if(empty($post['top_id'])){
            return json(['code'=>1, 'msg'=>'参数异常']);
        }

        $service = new JobCategoryService();
        return $service->getJobCategory((int)$post['top_id']);
    }

    /**
     * 删除：删除分类必须清空该分类下所有的子分类及职位
     * @return \think\response\Json|void
     */
    public function categoryDelete(){
        $post = $this->request->post();
        $id = (int)$post['id'];
        if(empty($id)){
            return json(['code'=>1, 'msg'=>'参数异常']);
        }

        $service = new JobCategoryService();
        return $service->delete($id);
    }
    /**
     * 新增岗位分类
     * @return mixed
     */
    public function categoryInsert()
    {
        $service = new JobCategoryService();
        if($this->request->isPost()) {
            $post = $this->request->post();
            $data = $post['field'];
            return $service->updateOrInsert($data);
        } else {
            $itemCategory = $service->getJobCategory();
            View::assign('category_list', $itemCategory);
            return View::fetch();
        }
    }
    /**
     * 编辑岗位分类
     * @throws view
     * @return Json
     */
    public function categoryEdit(){
        $service = new JobCategoryService();
        if($this->request->isPost()) {
            $post = $this->request->post();
            $id = $post['field'];
            if($id <= 0){
                return json(['code'=>1, 'msg'=>'id不正确']);
            }
            $data = $post['field'];
            return $service->updateOrInsert($data);
        } else {
            $id = $this->request->get('id');
            if($id <= 0){
                return json(['code'=>1, 'msg'=>'id不正确']);
            }
            $data = $service->getJobCategoryBy((int)$id);
            $itemCategory = $service->getJobCategory();
            $data['category_list'] = $itemCategory;
            $data['top_id'] = $service->getJobCategoryId($data['parent_id']);
            $data['category_list_child'] = ($data['top_id'] == 0) ? $service->getJobCategory($data['parent_id']) : $service->getJobCategory((int)$data['top_id']);
            View::assign('data',$data);
            return View::fetch();
        }
    }
}